package br.com.amigooo.repository;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import br.com.amigooo.model.User;
import br.com.amigooo.util.HibernateUtil;

public class UserImpl extends GenericHibernate<User> implements UserDao {

	@Override
	public User getUser(String email) {
		User user = null;
		Session session = null;

		try {
			session = HibernateUtil.getSessionFactory().openSession();
			user = (User) session.get(User.class, email);
			session.flush();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Set<User> getUsersList() {
		List<User> listUsers = new ArrayList<User>();
		Set<User> users = null;
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			listUsers = session.createQuery("from User").list();
			users = new HashSet<User>(listUsers);
			
			session.flush();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return users;
	}

	public User getUserAuth(String email, String password) {
		Session session = null;
		org.hibernate.Query query = null;
		User user = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			query = session.createQuery("from User where email = :email and userPassword = :password");
			query.setParameter("email", email);
			query.setParameter("password", password);
			user = (User) query.uniqueResult();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return user;
	}
}
